<template>
  <div>
    <!--新增/编辑安排提货弹窗-->
    <el-dialog
      :close-on-click-modal="false"
      :beforeClose="handleClose2"
      title="安排提货"
      :visible.sync="dialogVisible2"
      width="1200px">
      <el-row>
        <el-col :span="8">
          <div style="font-weight: bold;margin-bottom:10px;">需安排提货合同信息</div>
          <el-form>
            <el-form-item label="商品信息：" style="margin-bottom:0">
              {{ cutItem.goodsSn }}
            </el-form-item>
            <el-form-item label="客户名称：" style="margin-bottom:0">
              {{ cutItem.customerName }}
            </el-form-item>
            <el-form-item label="业务员：" style="margin-bottom:0">
              {{ cutItem.userRealName }}
            </el-form-item>
            <el-form-item label="合同数量：" style="margin-bottom:0">
              {{ cutItem.goodsNum }}
            </el-form-item>
            <el-form-item label="未发货数量：" style="margin-bottom:0" >
              {{ cutItem.unSendNum }}
            </el-form-item>
            <el-form-item label="已安排数量：" style="margin-bottom:0">
              {{ cutItem.planNum }}
            </el-form-item>
            <el-form-item label="未安排数量：" style="margin-bottom:0" >
              {{ cutItem.unPlanNum }}
            </el-form-item>
            <el-form-item label="发货类型：" style="margin-bottom:0">
              {{ cutItem.sendType }}
            </el-form-item>
            <el-form-item label="预计发货仓库：" style="margin-bottom:0" >
              {{ cutItem.warehouseName }}
            </el-form-item>
            <el-form-item label="订单备注：" style="margin-bottom:0" >
              <div style="color:red;font-size:16px;">{{ cutItem.goodsRemark }}</div>
            </el-form-item>
            <el-form-item label="结算方式：" style="margin-bottom:0">
              <span v-if="cutItem.orderRemark" :style="{color:(cutItem.orderRemark.indexOf('货到付款') != -1 || cutItem.orderRemark.indexOf('货到票到付款') != -1) ? 'red' : '#606266'}">{{ cutItem.orderRemark }}</span>
            </el-form-item>
            <el-form-item label="询盘备注：" style="margin-bottom:0" >
              <div style="color:red;font-size:16px;">{{ cutItem.freightRemark }}</div>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="16" style="border-left:1px solid #DCDFE6">
          <el-form :model="sendForm" size="mini" label-width="120px"  ref="sendForm" :rules="rules2">
            <el-form-item label="提货时间："  prop="takeTime">
              <el-date-picker
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd"
                v-model="sendForm.takeTime"
                style="display: inline-block;width:150px"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="提货概率：" prop="isSure">
              <el-radio-group v-model="sendForm.isSure">
                <el-radio :label="1">确定<span style="color:#999;padding-left:5px">(保证准时发货)</span></el-radio>
                <el-radio :label="0">不确定</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="提货数量："  prop="planNum">
              <el-input v-model="sendForm.planNum" style="width:200px;"></el-input>
            </el-form-item>
            <el-form-item label="商品包装："  prop="goodsWeight">
              <el-input v-model="sendForm.goodsWeight" style="width:150px"></el-input> <span>kg/包</span>
              <el-checkbox v-model="sendForm.isHasTray">含托</el-checkbox>
            </el-form-item>
            <el-form-item label="发同批次同产线："  prop="isSameBatch">
              <el-radio-group v-model="sendForm.isSameBatch">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="商品备注：">
               <el-input v-model="sendForm.goodsRemark"></el-input>
            </el-form-item>
            <el-form-item label="提货类型：" prop="planSendType" v-if="sendForm.isSure == 1">
              <el-radio-group v-model="sendForm.planSendType">
                <el-radio label="工厂发货">工厂发货</el-radio>
                <el-radio label="运联发货">运联发货</el-radio>
                <el-radio label="自提">自提</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="关联单类型：" prop="relationOrderType">
                <el-radio-group v-model="sendForm.relationOrderType" @change="changeRelationOrderType()">
                  <el-radio label="purchaseOrder">采购合同</el-radio>
                  <el-radio label="agentProcess">代加工单</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="关联单号：" prop="relationDetailIds">
              <el-select v-model="sendForm.relationDetailIds" clearable multiple style="width:100%" filterable>
                <el-option
                  :class="{'zdt-opt2':item.isShow ==1 && sendForm.relationOrderType == 'purchaseOrder'}"
                  :value="item.detailId" :label="item.purchaseSn+'/'+item.goodsSn+'/'+item.goodsNum+'吨/'+'/￥'+item.goodsPrice+'/可提'+item.unTakeNum+'吨'+'/'+item.supplierName" v-for="item in purchaseOrderArray" :key="item.detailId"></el-option>
              </el-select>
            </el-form-item>
            <div v-if="sendForm.planSendType != '工厂发货'">
              <el-form-item label="仓库：" prop="takeWarehouse">
                <el-select
                  style="width:250px;display: inline-block"
                  clearable
                  v-model="sendForm.takeWarehouse"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  @change="changeWarehouseId"
                  :remote-method="remoteMethod2"
                  :loading="loading">
                  <el-option
                    v-for="item in options2"
                    :key="item.warehouseId"
                    :label="item.warehouseName+' / '+item.warehouseAddress"
                    :value="item.warehouseName">
                  </el-option>
                </el-select>
                <el-button type="text" style="display: inline-block" @click="showDialog5">增加仓库</el-button>
              </el-form-item>
              <el-form-item label="联系人："  prop="contactName" >
                <el-input v-model="sendForm.contactName"  style="width:200px"></el-input>
              </el-form-item>
              <el-form-item label="手机号："  prop="contactMobile">
                <el-input v-model="sendForm.contactMobile" style="width:200px"></el-input>
              </el-form-item>
              <el-form-item label="提货地点："  prop="takeAddress">
                <el-input v-model="sendForm.takeAddress" style="width:80%" :autosize="{ minRows: 2, maxRows: 6}" type="textarea"></el-input>
              </el-form-item>
              <el-form-item label="注意事项：" >
                <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" v-model="sendForm.takeNote" style="width:80%"></el-input>
              </el-form-item>
              <el-form-item label="提货备注：" >
                <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" v-model="sendForm.takeRemark" style="width:80%"></el-input>

              </el-form-item>
              <el-form-item label="司机卸货：" v-if="sendForm.planSendType == '运联发货'" >
                <el-radio-group v-model="sendForm.isNeedDriverUnload">
                   <el-radio :label="1">是</el-radio>
                   <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <div v-if="sendForm.planSendType == '自提'">
                <el-form-item label="车牌号：" prop="driverTruckNo">
                  <el-input  style="width:200px" v-model="sendForm.driverTruckNo"></el-input>
                </el-form-item>
                <el-form-item label="司机姓名："  prop="driverName">
                  <el-input  style="width:200px" v-model="sendForm.driverName"></el-input>
                </el-form-item>
                <el-form-item label="手机号："  prop="driverMobile">
                  <el-input style="width:200px" v-model="sendForm.driverMobile"></el-input>
                </el-form-item>
                <el-form-item label="身份证：" >
                  <el-input style="width:200px" v-model="sendForm.driverIdNumber"></el-input>
                </el-form-item>
              </div>
            </div>

          </el-form>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>

    <!--增加仓库-->
    <warehouseInfo ref="warehouseInfo" @getList="getWarehouseList"></warehouseInfo>

  </div>
</template>
<script>
import "@/utils/jQuery.print"
import {getPlanList,goodsList,getUnPlanList,warehouseList,getWarehouseDetail,postPlanGoods,warehouseAdd,getPlanGoodsList,getGoodsPlanList,changePlanDate,cancelGoodsPlan,selfTakeInfo,ordGoodsFilter,planGoodsFilter} from '@/api/company'
import warehouseInfo from "./warehouseInfo.vue"
import {planOrderGoods,needTakePurchaseGoods,warehouseListPlan,checkPlanOrderIsPaid} from '@/api/order'
const defaultSendForm={
  "takeTime" : "", //提货时间
  "isSure" : 1, //提货概率(0不确定，1确定)
  "planSendType" : "工厂发货",  //提货类型:工厂发货、运联发货、自提
  "takeWarehouse" : "" ,//提货仓库
  "contactName" : "", //联系人
  "contactMobile" : "", //联系人手机号
  "takeAddress" : "",  //提货地址
  "takeRemark" : "原厂正牌，原料生产日期不超过合同签订日前六个月，外观无破损、潮湿，无大面积污渍，包装袋规格及颜色一致。", //提货备注
  "takeNote" : "", //注意事项
  "driverName" : "", //司机姓名
  "driverMobile" : "", //司机手机号
  "driverTruckNo" : "", //司机车牌号
  "driverIdNumber":'',
  "isNeedDriverUnload" : '', //是否需要司机卸货(0不需要，1需要)

  planNum   : '', //提货数量
  relationOrderType : "purchaseOrder", //关联的订单类型(采购单-purchaseOrder,代加工单-agentProcess)
  relationDetailIds : [], //关联的订单ID
  goodsWeight : '', //包装重量
  isHasTray : false,
  goodsRemark:'',
  isSameBatch:'',//是否同批次

};
export default {
  name: "printdischarging",
  data(){
    const isvalidatePurchaseOrderId = (rule, value, callback) => {
      if(this.sendForm.planSendType == '工厂发货' && value.length == 0&& this.cutItem.goodsSn.indexOf('备注型号')==-1 ){
        callback(new Error('请关联单号'))
      }else if(this.sendForm.planSendType == '运联发货' && this.curWarehouse.isSelfBusiness==0 && value.length == 0&& this.cutItem.goodsSn.indexOf('备注型号')==-1 ){
        callback(new Error('请关联单号'))
      } else if(this.sendForm.planSendType == '自提' && this.curWarehouse.isSelfBusiness==0 && value.length == 0&& this.cutItem.goodsSn.indexOf('备注型号')==-1 ){
        callback(new Error('请关联单号'))
      } else {
        callback()
      }
    };
    return {
      dialogVisible2:false,
      rules2:{
        takeWarehouse   :[{required: true, message: '请选择仓库', trigger: 'change'},],
        contactName   : [{required: true, message: '请输入联系人', trigger: 'blur'},],
        contactMobile : [{required: true, message: '请输入联系人手机号', trigger: 'blur'},],
        takeAddress   : [{required: true, message: '请输入提货地址', trigger: 'blur'},],
        takeTime      : [{required: true, message: '请输入提货时间', trigger: 'blur'},],
        planNum       : [{required: true, message: '请输入提货数量', trigger: 'blur'},],
        planSendType      : [{required: true, message: '请选择提货类型', trigger: 'change'},],
        relationDetailIds : [{required: true, validator: isvalidatePurchaseOrderId, trigger: 'change'},],
        goodsWeight: [{required: true, message: '请输入商品包装', trigger: 'blur'},],
        isSure:[{required: true, message: '请选择提货概率', trigger: 'change'},],
        driverTruckNo: [{required: true, message: '此项必填', trigger: 'blur'},],
        driverName: [{required: true, message: '此项必填', trigger: 'blur'},],
        driverMobile: [{required: true, message: '此项必填', trigger: 'blur'},],
        isSameBatch:[{required: true, message: '此项必填', trigger: 'change'},],
      },
      btnLoading2:false,
      sendForm:JSON.parse(JSON.stringify(defaultSendForm)),
      dialogVisible3:false,
      options2:[],
      goodsPlanList:[],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      cutItem:{},
      purchaseOrderList:[],
      curWarehouse:{},
      listLoading:false,
      loading:false,
      purchaseOrderArray:[],

    }
  },

  components : {
    warehouseInfo:warehouseInfo
  },

  filters:{

  },

  created() {

  },

  methods:{
    //获取关联采购单
    remoteMethod(goodsKingId,relationOrderType,){
      return needTakePurchaseGoods({
        goodsKingId: goodsKingId,
        orderType: relationOrderType,
        fromCompany:this.cutItem.fromCompany,
        orderId:this.cutItem.orderId
      }).then((res) => {
        this.purchaseOrderArray = res;
      })
    },

    //切换关联类型
    changeRelationOrderType(){
      this.sendForm.relationOrderId = [];
      this.remoteMethod(this.cutItem.goodsKingId,this.sendForm.relationOrderType);
    },

    //显示增加仓库弹窗
    showDialog5(){
      this.$refs.warehouseInfo.showDialog('add',null);
    },
    //仓库列表
    getWarehouseList(keywords,warehouseId){
      warehouseListPlan({keywords:keywords}).then((res)=>{
        this.options2 = res;
        this.btnLoading5 = false;
        if(warehouseId){
          this.changeWarehouseId(keywords);
          this.sendForm.takeWarehouse = keywords
        }
      })
    },
    //搜索仓库
    remoteMethod2(query) {
      if (query !== '') {
        this.loading2 = true;
        warehouseListPlan({keywords:query}).then((res)=>{
          this.options2 = res;
          this.loading2 = false;
        })
      } else {
        this.options = [];
        this.loading2 = false;
      }
    },

    changeWarehouseId(val){
      let curWarehouse = this.options2.find((el)=>{
        return el.warehouseName == val
      });
      this.curWarehouse = JSON.parse(JSON.stringify(curWarehouse));
      if(curWarehouse.warehouseId){
        // getWarehouseDetail({warehouseId:curWarehouse.warehouseId}).then((res)=>{
          this.sendForm.contactName  = this.curWarehouse.contactName;
          this.sendForm.contactMobile = this.curWarehouse.contactMobile;
          this.sendForm.takeAddress = this.curWarehouse.warehouseAddress;
          this.sendForm.takeNote = this.curWarehouse.takeNote;
        // });
      }else{
        this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
      }
    },

    //显示提货信息
    showDialog3(item){
      console.log("item",item)
      this.cutItem = JSON.parse(JSON.stringify(item));
      this.showDialog2('add')
    },

    //关闭提货
    handleClose3(){
      this.dialogVisible3 = false;
      this.$emit('getList')
    },

    //显示安排提货
    showDialog2(type,item,tab){
      this.dialogVisible2 = true;
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
      this.options2 = [];
      this.sendForm.planNum = this.cutItem.unPlanNum;
      this.sendForm.isSameBatch = this.cutItem.isSameBatch;
      this.remoteMethod(this.cutItem.goodsKingId,'purchaseOrder') // 获取关联采购单
    },

    //关闭安排提货
    handleClose2(){
      this.dialogVisible2 = false;
      this.$refs.sendForm.clearValidate();
    },

    //提交安排提货
    handleConfirm2(){
      this.$refs['sendForm'].validate((valid) => {
        if (valid) {
          let pa = JSON.parse(JSON.stringify(this.sendForm));
          pa.isNeedDriverUnload = pa.isNeedDriverUnload ? 1 : 0;
          if(pa.planSendType == '工厂发货'){
            pa.takeWarehouse = '';
            pa.contactName = '';
            pa.contactMobile = '';
            pa.takeAddress = '';
            pa.takeRemark = '';
            pa.takeNote = '';
            pa.isNeedDriverUnload = 0;
            pa.driverName = '';
            pa.driverMobile = '';
            pa.driverTruckNo = '';
            pa.driverIdNumber = '';
          }else if(pa.planSendType == '运联发货'){
            pa.driverName = '';
            pa.driverMobile = '';
            pa.driverTruckNo = '';
            pa.driverIdNumber = ''
          }else if(pa.planSendType == '自提'){
            pa.isNeedDriverUnload = 0;
          }
          pa.detailData = [];
          pa.detailData.push({
            detailId  : this.cutItem.ogId,
            planNum   : this.sendForm.planNum, //提货数量
            relationOrderType : this.sendForm.relationOrderType, //关联的订单类型(采购单-purchaseOrder,代加工单-agentProcess)
            relationDetailIds : this.sendForm.relationDetailIds, //关联的订单ID
            goodsWeight : this.sendForm.goodsWeight, //包装重量
            isHasTray : this.sendForm.isHasTray ? 1 : 0, //是否含托(1是，0否)
            goodsRemark : this.sendForm.goodsRemark,
          })
          this.isPopConfirm(pa)
        }
      })
    },

    //排货提示判断
    isPopConfirm(data){
      console.log("data",data);
      let pa = {};
      pa.detailData = JSON.parse(JSON.stringify(data.detailData))
      checkPlanOrderIsPaid(pa).then((res)=>{
         let msg = ''
         if(res.isHasUnPaidAmount == 1 && res.isNotEnoughPaidAmount == 1){
           msg = '排货客户存在未结清的历史订单并且排货客户订单付款金额不足，请确认是否排货？'
         }else if(res.isHasUnPaidAmount == 1){
           msg = '排货客户存在未结清的历史订单，请确认是否排货？'
         }else if(res.isNotEnoughPaidAmount == 1){
           msg = '排货客户订单付款金额不足，请确认是否排货？'
         }
         if(msg != ''){
           this.$confirm(msg, '提示', {
             confirmButtonText: '继续排货',
             cancelButtonText: '取消排货',
             type: 'warning'
           }).then(() => {
             this.btnLoading2 = true;
              this.pushPH(data)
           }).catch(() => {
             // this.btnLoading2 = false;
             this.dialogVisible2 = false;
           });
         }else{
           this.btnLoading2 = true;
            this.pushPH(data)
         }
      })
    },

    //提交排货
    pushPH(pa){
      planOrderGoods(pa).then((res)=>{
        this.btnLoading2 = false;
        this.dialogVisible2 = false;
        if(res.isPurchaseHasUnPaid == 1){
          this.$message({
            message: '当前关联采购合同未付款，请尽快安排付款',
            type: 'warning'
          });
        }
        this.$emit('getList')
      }).catch(()=>{
        this.btnLoading2 = false;
      })
    }

  },
}
</script>

<style scoped lang="scss">
.zdt-opt2{
  color:red
}
</style>
